#!/usr/bin/env python
# -*- encoding: UTF-8 -*-
from __future__ import print_function

import os
import cv2

# 导入数据库
from .. import db
from .. import basedir as app_dir

# 图片模型，每一张篇附属于一个相机，图片数据库中只保存图像的索引
# 图像文件保存在 app/data 文件夹中，以 img_<index>.jpg 命名
class Image(db.Model):
    __tablename__ = "images"
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(80),default="")
    cam_id = db.Column(db.Integer,db.ForeignKey('cams.id'))

    def __init__(self,cam, name=None):
        from .Cam import Cam
        assert isinstance(cam,Cam)
        self.cam=cam
        if name is None:
            name = ""
        self.name=name

    @classmethod
    def get(cls,id):
        return cls.query.get(id)

    @classmethod
    def get_cam_flag(cls,cam_id,flag):
        out = cls.query.filter_by(cam_id=cam_id,name=flag).all()
        return out

    @classmethod
    def remove_invalid_images(cls):
        # 移除无效的图像
        for image in cls.query.all():
            data_dir = os.path.join(app_dir,'data')
            filename = os.path.join(data_dir,'img_%d'%image.id+".jpg")
            if not os.path.exists(filename):
                db.session.delete(image)
        db.session.commit()

    def commit(self):
        db.session.add(self)
        db.session.commit()
        return db.session.merge(self)

    def get_filename(self):
        data_dir = os.path.join(app_dir,'data')
        if not os.path.exists(data_dir):
            os.mkdir(data_dir)
        filename = os.path.join(data_dir,'img_%d'%self.id + ".jpg")
        return filename

    def get_image(self):
        filename = self.get_filename()
        assert os.path.exists(filename)
        return cv2.imread(filename=filename)

    def remove_image(self):
        filename = self.get_filename()
        os.remove(filename)

    def save(self,image):
        filename = self.get_filename()
        cv2.imwrite(filename,image)